package com.icen.utils.comm;

import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * Veiws Utils Class
 * 
 * @author IcenHan
 * 
 */
public class ViewsUtils {

	/**
	 * 获取控件中的值
	 * <p>
	 * 目前支持: EditText, TextView
	 * </p>
	 * 
	 * @param view
	 * @return String
	 */
	public static String getValue(View view) {
		if(view != null){
			if (view instanceof EditText) {
				return ((EditText) view).getText().toString().trim();
			} else if (view instanceof TextView) {
				return ((TextView) view).getText().toString().trim();
			}
		}
		return "";
	}

	/**
	 * 获取控件宽
	 * 
	 * @param view
	 * @return int
	 */
	public static int getViewWidth(View view) {
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		view.measure(w, h);
		return (view.getMeasuredWidth());
	}

	/**
	 * 获取控件高
	 * 
	 * @param view
	 * @return int
	 */
	public static int getViewHeight(View view) {
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		view.measure(w, h);
		return (view.getMeasuredHeight());
	}

	/**
	 * 设置控件所在的位置X,并且不改变宽高,X为绝对位置,此时Y可能归0
	 * 
	 * @param view
	 * @param x
	 */
	public static void setViewLayoutX(View view, int x) {
		MarginLayoutParams margin = new MarginLayoutParams(
				view.getLayoutParams());
		margin.setMargins(x, margin.topMargin, x + margin.width,
				margin.bottomMargin);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				margin);
		view.setLayoutParams(layoutParams);
	}

	/**
	 * 设置控件所在的位置Y,并且不改变宽高,Y为绝对位置,此时X可能归0
	 * 
	 * @param view
	 * @param y
	 */
	public static void setViewLayoutY(View view, int y) {
		MarginLayoutParams margin = new MarginLayoutParams(
				view.getLayoutParams());
		margin.setMargins(margin.leftMargin, y, margin.rightMargin, y
				+ margin.height);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				margin);
		view.setLayoutParams(layoutParams);
	}

	/**
	 * 设置控件所在的位置XY,并且不改变宽高,XY为绝对位置
	 * 
	 * @param view
	 * @param x
	 * @param y
	 */
	public static void setViewLayout(View view, int x, int y) {
		MarginLayoutParams margin = new MarginLayoutParams(
				view.getLayoutParams());
		margin.setMargins(x, y, x + margin.width, y + margin.height);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				margin);
		view.setLayoutParams(layoutParams);
	}
}
